package com.gap.employee;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Page.Group;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.formatter.DateFormatter;
import com.buanalintas.bynga.formatter.MoneyFormatter;
import com.gap.entities.GapMasterEmployee;
import com.gap.entities.GapMasterHistoryEmployee;
import com.gap.entities.GapMasterItem;
import com.gap.entities.GapTransactionEmployee;
import com.gap.entities.GapTransactionEmployeeDetail;
import com.gap.entities.GapTransactionHistoryEmployee;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * Class Employee is ...
 *
 * Generated on Fri Jan 09 13:17:48 ICT 2015
 *
 * @version 1.0
 * @author Mr. Kazao™
 * @since Bynga 1.0
 *
 */
public class TransactionEmployee extends Page {

    private Field posId;
    private Field posEmployeeName;
    private Field posEmployeeStatus;
    private Field posDate;
    private Field posNumber;
    private Field posPlatform;
    private Field posItemId;
    private Field posItemPrice;
    private Field posDiscount;
    private Field posValue;
    private Field posCurrent;
    private Field posLast;
    private Field posTimestamp;
    private Field posUserId;
    private Field posUnitId;
    private Field posEmployeeId;
    private Field posDescription;

    public TransactionEmployee() {
        super();

        setTheClass(GapTransactionEmployee.class);
        setPageDetail(TransactionEmployeeDetail.class);

        posId = new Field();
        posId.setName("posId");
        posId.setCaption("id");
        //posId.setInfo("pos id");
        posId.setListProperties(" align=\"center\" width=\"1%\" nowrap");
        posId.setInputProperties(" size=\"20\"");
        getFields().add(posId);

        posEmployeeName = new Field();
        posEmployeeName.setName("posEmployeeName");
        posEmployeeName.setCaption("employee name");
        posEmployeeName.setRequired(true);
        posEmployeeName.setListProperties(" align=\"left\" width=\"20%\" nowrap");
        posEmployeeName.setInputProperties(" size=\"50\" readonly");
        getFields().add(posEmployeeName);

        posEmployeeStatus = new Field();
        posEmployeeStatus.setName("posEmployeeStatus");
        posEmployeeStatus.setCaption("status bonus");
        posEmployeeStatus.setRequired(true);
        posEmployeeStatus.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        posEmployeeStatus.setInputProperties(" size=\"10\" readonly");
        getFields().add(posEmployeeStatus);

        posDate = new Field();
        posDate.setName("posDate");
        posDate.setCaption(" date");
        posDate.setRequired(true);
        posDate.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        posDate.setInputProperties(" size=\"8\"");
        posDate.setDefaultValue(Utility.getTimestamp());
        getFields().add(posDate);

        posNumber = new Field();
        posNumber.setName("posNumber");
        posNumber.setCaption("number");
        posNumber.setRequired(true);
        posNumber.setListProperties(" align=\"center\" width=\"15%\" nowrap");
        posNumber.setInputProperties(" size=\"20\" readonly");
        getFields().add(posNumber);

        posPlatform = new Field();
        posPlatform.setName("posPlatform");
        posPlatform.setCaption("platform");
        posPlatform.setRequired(true);
        posPlatform.setFormater(MoneyFormatter.getInstance());
        posPlatform.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        posPlatform.setInputProperties(" size=\"20\" readonly");
        getFields().add(posPlatform);

        posItemId = new Field();
        posItemId.setName("posItemId");
        posItemId.setCaption("item");
        posItemId.setRequired(true);
        posItemId.setListProperties(" align=\"left\" width=\"15%\" nowrap");
        posItemId.setInputProperties(" size=\"30\" ");
        getFields().add(posItemId);

        posItemPrice = new Field();
        posItemPrice.setName("posItemPrice");
        posItemPrice.setCaption("price");
        posItemPrice.setRequired(true);
        posItemPrice.setDefaultValue(0);
        posItemPrice.setFormater(MoneyFormatter.getInstance());
        posItemPrice.setInputCase(Field.CASE_UPPER);
        posItemPrice.setListProperties(" align=\"right\" width=\"10%\" nowrap");
        posItemPrice.setInputProperties(" size=\"20\"");
        getFields().add(posItemPrice);

        posDiscount = new Field();
        posDiscount.setName("posDiscount");
        posDiscount.setCaption("discount percent");
        posDiscount.setRequired(true);
        posDiscount.setDefaultValue(0);
//        posDiscount.setFormater(MoneyFormatter.getInstance());
        posDiscount.setListProperties(" align=\"right\" width=\"10%\" nowrap");
        posDiscount.setInputProperties(" size=\"20\"");
        getFields().add(posDiscount);

        posValue = new Field();
        posValue.setName("posValue");
        posValue.setCaption("value");
        posValue.setRequired(true);
        posValue.setDefaultValue(0);
        posValue.setFormater(MoneyFormatter.getInstance());
        posValue.setListProperties(" align=\"right\" width=\"10%\" nowrap");
        posValue.setInputProperties(" size=\"20\"");
        getFields().add(posValue);

        posCurrent = new Field();
        posCurrent.setName("posCurrent");
        posCurrent.setCaption("saldo");
        posCurrent.setRequired(true);
        posCurrent.setDefaultValue(0);
        posCurrent.setFormater(MoneyFormatter.getInstance());
        posCurrent.setListProperties(" align=\"right\" width=\"10%\" nowrap");
        posCurrent.setInputProperties(" size=\"20\"");
        getFields().add(posCurrent);

        posLast = new Field();
        posLast.setName("posLast");
        posLast.setCaption("last");
        posLast.setRequired(true);
        posLast.setDefaultValue(0);
        posLast.setFormater(MoneyFormatter.getInstance());
        posLast.setInputCase(Field.CASE_UPPER);
        posLast.setListProperties(" align=\"right\" width=\"1%\" nowrap");
        posLast.setInputProperties(" size=\"20\"");
        getFields().add(posLast);

        posTimestamp = new Field();
        posTimestamp.setName("posTimestamp");
        posTimestamp.setCaption("timestamp");
        //posTimestamp.setInfo("pos timestamp");
        posTimestamp.setListProperties(" align=\"center\" width=\"1%\" nowrap");
        posTimestamp.setInputProperties(" size=\"12\"");
        //posTimestamp.setFormatter(DateFormatter.getInstanceDateTime(this));
        getFields().add(posTimestamp);

        posUserId = new Field();
        posUserId.setName("posUserId");
        posUserId.setCaption("user");
        //posUserId.setInfo("pos user id");
        posUserId.setListProperties(" align=\"center\" width=\"1%\" nowrap");
        posUserId.setInputProperties(" size=\"20\"");
        getFields().add(posUserId);

        posUnitId = new Field();
        posUnitId.setName("posUnitId");
        posUnitId.setCaption("unit");
        //posUnitId.setInfo("pos unit id");
        posUnitId.setListProperties(" align=\"center\" width=\"1%\" nowrap");
        posUnitId.setInputProperties(" size=\"20\"");
        getFields().add(posUnitId);

        posEmployeeId = new Field();
        posEmployeeId.setName("posEmployeeId");
        posEmployeeId.setCaption("employee");
        posEmployeeId.setRequired(true);
        posEmployeeId.setListProperties(" align=\"center\" width=\"1%\" nowrap");
        posEmployeeId.setInputProperties(" size=\"30\"");
        posEmployeeId.setSelectorOrder("t.employeeNumber");
        posEmployeeId.setSelectorCondition("t.employeeActive='1'");
        posEmployeeId.getSelectorAction().add(new String[]{"value", "posEmployeeName", "employeeNameFirst"});
        posEmployeeId.getSelectorAction().add(new String[]{"value", "posPlatform", "employeePlatform"});
        posEmployeeId.getSelectorAction().add(new String[]{"value", "posEmployeeStatus", "employeeStatusBonus"});
        posEmployeeId.getSelectorColumns().add(new String[]{"employeeNumber", "ID", "width=\"20%\" nowrap"});
        posEmployeeId.getSelectorColumns().add(new String[]{"employeeNameFirst", "Name", "width=\"50%\""});
        posEmployeeId.getSelectorColumns().add(new String[]{"employeePlatform", "Platform", "width=\"15%\" nowrap"});
        posEmployeeId.getSelectorColumns().add(new String[]{"employeeStatusBonus", "status", "width=\"5%\" nowrap"});
        getFields().add(posEmployeeId);

        posDescription = new Field();
        posDescription.setName("posDescription");
        posDescription.setCaption(" description");
        //revisionDescription.setInfo("revision description");
        posDescription.setListProperties(" width=\"20%\"");
        posDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        posDescription.setInputType(Field.INPUT_TEXT_AREA);
        getFields().add(posDescription);

        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);
        fillFields();

        getGroupsAdd().add(new Group("Transaction",
                posDate,
                posNumber));
        getGroupsAdd().add(new Group("Employee",
                posEmployeeId,
                posEmployeeName,
                posPlatform,
                posEmployeeStatus));
        

        getGroupsEdit().add(new Group("Transaction",
                posDate,
                posNumber));
        getGroupsEdit().add(new Group("Employee",
                posEmployeeId,
                posEmployeeName,
                posPlatform,
                posEmployeeStatus));

        getFieldsList().clear();
        getFieldsList().add(posDate);
        getFieldsList().add(posNumber);
        getFieldsList().add(posEmployeeId);
        getFieldsList().add(posEmployeeName);
        getFieldsList().add(posPlatform);
        getFieldsList().add(posEmployeeStatus);
        getFieldsList().add(posLast);
        getFieldsList().add(posValue);
        getFieldsList().add(posCurrent);
        getFieldsList().add(posDescription);

        getGroupsView().add(new Group("Transaction",
                posDate,
                posUnitId,
                posUserId,
                posTimestamp,
                posNumber));
        getGroupsView().add(new Group("Employee",
                posEmployeeId,
                posEmployeeName,
                posPlatform,
                posEmployeeStatus));
        getGroupsView().add(new Group("Saldo",
                posLast, posValue, posCurrent));


        setController(new TransactionEmployeeController(this));
        setExportList(getClass().getResourceAsStream("TransEmployeeList.jasper"));
        setExport(getClass().getResourceAsStream("TransEmployee.jasper"));
    }

    @Override
    public void afterInit(HttpServletRequest req, HttpServletResponse res) {
        posDate.setFormater(DateFormatter.getInstanceDate(this));
        posTimestamp.setFormater(DateFormatter.getInstanceDateTime(this));

    }

    @Override
    public String validate(Object data, List list) {
        HttpSession session = getRequest().getSession();
        EntityManager em = getEntityManager();
        GapTransactionEmployee employ = (GapTransactionEmployee) data;
        GapMasterHistoryEmployee masterHis = Employee.getStock(em, employ.getPosEmployeeId());
        BigDecimal cek = employ.getPosCurrent();

        GapMasterItem item = null;
        //---Item---
        try {
            item = (GapMasterItem) em.createQuery("SELECT t FROM GapMasterItem t WHERE t.itemId='" + employ.getPosItemId().getItemId() + "'").setHint(Persistence.REFRESH_HINT, true).getSingleResult();
            System.out.println("x item  ---->" + item);
        } catch (Exception e) {
            System.out.println("x salahe item  ---->" + e);
        }
        //----- PRICE ITEM------
        BigDecimal totNet = BigDecimal.ZERO;

            for (int i = 0; i < list.size(); i++) {
                List<GapTransactionEmployeeDetail> details = list;
                totNet = totNet.add(details.get(i).getPosDetailNett());
            }
            //---------------

        //--- DATE TRANSAKSI-----------
        Date date = employ.getPosDate();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int month = cal.get(Calendar.MONTH) + 1;
        System.out.println("MONTH ---->" + month);

        //---DATE MASTER HISTORY-------    
        Date date2 = new Date();
        Calendar cal2 = Calendar.getInstance();
        int month2 = 0;
        if (masterHis.getHistoryDate() != null) {
            date2 = masterHis.getHistoryDate();
            cal2.setTime(date2);
            month2 = cal2.get(Calendar.MONTH) + 1;
            System.out.println("x MONTH 1 ---->" + month2);
        }
        System.out.println("x MONTH 1 nuaa---->" + month2);

        //----value master history------
        int value = masterHis.getHistoryValue().intValue();
        System.out.println("x value 1 ---->" + value);


        BigDecimal Saldo = BigDecimal.ZERO;
        if (employ.getPosEmployeeStatus().equals("Gross")) {
            if (value == 0 && masterHis.getHistoryDate() == null) {
                Saldo = employ.getPosPlatform().subtract(totNet);
                System.out.println("Saldo 2 iiii---->" + Saldo);
            } else if (month == 7 && value >= 0) {
                Saldo = (employ.getPosPlatform().add(masterHis.getHistoryValue()))
                        .subtract(totNet);
                System.out.println("Saldo 2 aaaa---->" + Saldo);
            } else {
                Saldo = masterHis.getHistoryValue().subtract(totNet);
                System.out.println("Saldo 2 uuuu---->" + Saldo);
            }
            System.out.println("x Saldo 2 ---->" + Saldo);

        } else if (employ.getPosEmployeeStatus().equals("Periodik")) {



            int beb = 0;

            if (month > 6) {
                beb = month - 6;
                System.out.println("x beb 1---->" + beb);
            } else {
                beb = 6 + month;
                System.out.println("x beb 2---->" + beb);
            }

            BigDecimal b = new BigDecimal(beb);
            BigDecimal bln = new BigDecimal(12);
            System.out.println("x bln ---->" + bln);
            if (masterHis.getHistoryDate() == null) {
                Saldo = ((employ.getPosPlatform().divide(bln, 2, RoundingMode.HALF_UP).multiply(b))
                        .subtract(masterHis.getHistoryValue()))
                        .subtract(totNet);
                System.out.println("x Saldo 1 uuuu---->" + Saldo);
            } else if (month == month2 && value == 0) {
                Saldo = new BigDecimal(-1);
            } else if (month == month2 && value > 0) {
                Saldo = masterHis.getHistoryValue().subtract(totNet);
                System.out.println("x Saldo 1 aaaaa---->" + Saldo);
            } else {
                Saldo = ((employ.getPosPlatform().divide(bln, 2, RoundingMode.HALF_UP).multiply(b))
                        .subtract(masterHis.getHistoryValue()))
                        .subtract(totNet);
                System.out.println("x Saldo 1 aaaaa---->" + Saldo);
            }
            System.out.println("x Saldo 1 ---->" + Saldo);
        }

        System.out.println(" x ---> Saldo =" + Saldo
                + " x ---> harga =" + employ.getPosItemPrice());

//        BigDecimal ini = employ.getPosValue().add((employ.getPosItemPrice().subtract(employ.getPosDiscountNominal()))).subtract(masterHis.getHistoryValue());
        if (Saldo.intValue() < 0) {
            return Dictionary.getValue(this, "Saldo bulan ini sebesar Rp " + value
                    + " dan nilai transaksi anda sebesar Rp " + totNet);
        }

        return null;
    }

    @Override
    public void beforeAdd() {
        posNumber.setDefaultValue(generate());
    }

    class TransactionEmployeeController extends Controller {

        public TransactionEmployeeController(Page page) {
            super(page);
            setOrder(posTimestamp);
            setOrderType("DESC");
        }

        @Override
        public void beforeInsert(Object data, List detail) {
            EntityManager em = getEntityManager();
            GapTransactionEmployee employee = (GapTransactionEmployee) data;
            employee.setPosNumber(generate());
            employee.setPosUnitId(getCurrentUnit());
            employee.setPosUserId(getCurrentUser());
            employee.setPosTimestamp(Utility.getTimestamp());

            GapMasterHistoryEmployee masterhis = Employee.getStock(em, employee.getPosEmployeeId());
            GapTransactionHistoryEmployee history = new GapTransactionHistoryEmployee();

            employee.setPosLast(masterhis.getHistoryValue());

            BigDecimal Saldo = BigDecimal.ZERO;

            BigDecimal totNet = BigDecimal.ZERO;

            for (int i = 0; i < detail.size(); i++) {
                List<GapTransactionEmployeeDetail> details = detail;
                totNet = totNet.add(details.get(i).getPosDetailNett());
            }

            employee.setPosValue(totNet);
            //--- DATE TRANSAKSI-----------
            Date date = employee.getPosDate();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int month = cal.get(Calendar.MONTH) + 1;
            System.out.println("MONTH ---->" + month);

            //---DATE MASTER HISTORY-------    
            Date date2 = new Date();
            Calendar cal2 = Calendar.getInstance();
            int month2 = 0;
            if (masterhis.getHistoryDate() != null) {
                date2 = masterhis.getHistoryDate();
                cal2.setTime(date2);
                month2 = cal2.get(Calendar.MONTH) + 1;
                System.out.println("x MONTH 1 ---->" + month2);
            }

            //----value master history------
            int value = masterhis.getHistoryValue().intValue();
            System.out.println("x value 1 ---->" + value);

            GapMasterEmployee mase = null;
            try {
                mase = (GapMasterEmployee) em.createQuery("SELECT t FROM GapMasterEmployee t WHERE t.employeeId='" + employee.getPosEmployeeId().getEmployeeId() + "'").setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                System.out.println("mase ---->" + mase);
                System.out.println("bonus ---->" + mase.getEmployeeStatusBonus());
                if (employee.getPosEmployeeStatus().equals("Gross")) {
                    if (value == 0 && masterhis.getHistoryDate() == null) {
                        Saldo = employee.getPosPlatform().subtract(totNet);
                        System.out.println("Saldo 2 iiii---->" + Saldo);
                        employee.setPosCurrent(Saldo);
                    } else if (month == 7 && value >= 0) {
                        Saldo = (employee.getPosPlatform().add(masterhis.getHistoryValue()))
                                .subtract(totNet);
                        System.out.println("Saldo 2 aaaa---->" + Saldo);
                        employee.setPosCurrent(Saldo);
                    } else {
                        Saldo = masterhis.getHistoryValue().subtract(totNet);
                        System.out.println("Saldo 2 uuuu---->" + Saldo);
                        employee.setPosCurrent(Saldo);
                    }
                    System.out.println("x Saldo 2 ---->" + Saldo);

                } else if (employee.getPosEmployeeStatus().equals("Periodik")) {

                    int beb = 0;

                    if (month > 6) {
                        beb = month - 6;
                        System.out.println(" beb 1---->" + beb);
                    } else {
                        beb = 6 + month;
                        System.out.println(" beb 2---->" + beb);
                    }

                    BigDecimal b = new BigDecimal(beb);
                    BigDecimal bln = new BigDecimal(12);
                    System.out.println(" bln ---->" + bln);
                    if (masterhis.getHistoryDate() == null) {
                        Saldo = ((employee.getPosPlatform().divide(bln, 2, RoundingMode.HALF_UP).multiply(b))
                                .subtract(masterhis.getHistoryValue()))
                                .subtract(totNet);
                        System.out.println(" Saldo 1 uuuu---->" + Saldo);
                        employee.setPosCurrent(Saldo);
                    } else if (month == month2 && value == 0) {
                        Saldo = new BigDecimal(-1);
                        employee.setPosCurrent(masterhis.getHistoryValue());
                    } else if (month == month2 && value > 0) {
                        Saldo = masterhis.getHistoryValue().subtract(totNet);
                        System.out.println("x Saldo 1 aaaaa---->" + Saldo);
                        employee.setPosCurrent(Saldo);
                    } else {
                        Saldo = ((employee.getPosPlatform().divide(bln, 2, RoundingMode.HALF_UP).multiply(b))
                                .subtract(masterhis.getHistoryValue()))
                                .subtract(totNet);
                        System.out.println("x Saldo 1 aaaaa---->" + Saldo);
                        employee.setPosCurrent(Saldo);
                    }
                    System.out.println("x Saldo 1 ---->" + Saldo);
                }
            } catch (Exception e) {
                Logger.getInstance().log(e);
                System.out.println("eeeeee :" + e);
            }
        }
        
        
        @Override
        public void afterInsert(Object data) {
            EntityManager em = getEntityManager();
            em.getTransaction().begin();
            GapTransactionEmployee e = (GapTransactionEmployee) data;
            GapMasterHistoryEmployee masterhis = Employee.getStock(em, e.getPosEmployeeId());
            GapTransactionHistoryEmployee history = new GapTransactionHistoryEmployee();

            history.setHistoryId(Sequence.next(history));
            history.setHistoryEmployeeId(e.getPosEmployeeId());
            history.setHistoryUnitId(getCurrentUnit());
            history.setHistoryUserId(getCurrentUser());
            history.setHistoryDate(e.getPosDate());
            history.setHistoryStatus("Done");
            history.setHistoryType("1");
            history.setHistoryNumber(e.getPosNumber());
            history.setHistoryEmployeeName(e.getPosEmployeeName());
            history.setHistoryPlatform(e.getPosPlatform());
            history.setHistoryLast(masterhis.getHistoryValue());
            history.setHistoryCurrent(e.getPosCurrent());
            history.setHistoryValue(e.getPosValue());
            history.setHistoryDescription(e.getPosDescription());
            history.setHistoryTimestamp(e.getPosTimestamp());
            em.persist(history);
            masterhis.setHistoryValue(history.getHistoryCurrent());
            System.out.println("Curreennnttt ---->" + history.getHistoryCurrent() + " master his :" + masterhis.getHistoryValue());
            masterhis.setHistoryTimestamp(history.getHistoryTimestamp());
            masterhis.setHistoryUnitId(history.getHistoryUnitId());
            masterhis.setHistoryEmployeeId(history.getHistoryEmployeeId());
            masterhis.setHistoryEmployeeName(history.getHistoryEmployeeName());
            masterhis.setHistoryPlatform(history.getHistoryPlatform());
            masterhis.setHistoryDate(e.getPosDate());

            em.getTransaction().commit();
        }

    }

    public String generate() {
        String unitCode = getCurrentUnit().getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            GapTransactionEmployee employee = (GapTransactionEmployee) getEntityManager().createQuery("SELECT t FROM GapTransactionEmployee t WHERE t.posNumber LIKE '%/" + unitCode + "/GAP/%/" + year + "' ORDER BY t.posTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(employee.getPosNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/GAP/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/GAP/" + month + "/" + year;
    }

    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Transaction Employee"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();
    }
}
